#!/usr/bin/python2.4
# _*_ coding: utf-8-*-

import sys
import glob
from google.python import gflags 

flags = gflags
FLAGS= gflags.FLAGS

flags.DEFINE_string('file_pattern', '*.txt',
    'The log files pattern')

flags.DEFINE_string('output_prefix', 'test',
    'The prefix of the output file name')

flags.DEFINE_integer('article_per_page', 1000,
    'Number of articles per page')

PAGE_HEADER = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML> 

<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=gb2312"/> 
<TITLE>MIT Board </TITLE>
<link rel="stylesheet" type="text/css" href="style1.css">
<META NAME="author" CONTENT="Shashank Khanvilkar">
<META NAME="ROBOTS" CONTENT="ALL">
</HEAD>
 
<BODY BGCOLOR="#FFFFFF">

<CENTER>
<TABLE BORDER=0 CELLSPACING=3 COL=5 WIDTH=90%>
<TR>
<TD CLASS=header COLSPAN=5>:: MITBBS Board :: </TD>
</TR>
<TR>
<TD CLASS=home COLSPAN=4><A HREF="/">HOME</A></TD>
</TR>
</TABLE> 
"""

SHARD_HEADER = "Page [%d-%d] "

TABLE_HEADER = """
  <TABLE BORDER=1 WIDTH=80%> 
  <TR CLASS=header> 
  <TD> SN  </TD>
  <TD> Name </TD>
  <TD> Topic </TD>
  <TD> Link </TD>
  <TD> IP </TD>
  </TR> 
"""

TABLE_ROW = """
<TR>
  <TD>%(sn)s</TD>
  <TD>%(name)s</TD>
  <TD><a href="%(link)s">%(topic)s</a></TD>
  <TD>%(sametopic)s</TD>
  <TD>%(ip)s</TD>
</TR>
"""

TABLE_FOOTER = "</TABLE>"

PAGE_FOOTER = """
</CENTER>
</BODY> 
</HTML>
"""

def main(argv):
  argv = FLAGS(argv)           # handles help as well

  for f in glob.glob(FLAGS.file_pattern):
    DumpFile(f)

def DumpFile(fname):
  f = open(fname, 'r')
  s = f.read().splitlines()
  f.close()
  # TODO: parse the header and get board name.
  header_offset = 5
  s= s[header_offset:]
  shard_num = (len(s) - header_offset) / FLAGS.article_per_page
  for i in range(shard_num + 1):
    DumpShard(s, FLAGS.article_per_page, i, FLAGS.output_prefix)

def GetPageHeader(file_prefix, total_len, shard_size, i):
  page_links = []
  page_links.append("Page:")
  for j in range(0,  total_len/shard_size + 1):
    s = j * shard_size
    e = s + shard_size
    if e > total_len:
      e = total_len
    if i == j:
      page_links.append("[%d - %d]" % ( s, e))
    else:
      other_fname = file_prefix + "_%d" % j + ".html"
      page_links.append("[<a href='%s'>%d - %d<a>]" % (other_fname, s, e))
  return " ".join(page_links)
      
def DumpShard(s, shard_size, i, file_prefix):
  if not file_prefix:
    fout = sys.stdout
  else:
    fname = file_prefix + "_%d" % i + ".html"
    fout = open(fname, "w")
  total_len = len(s)

  fout.write(PAGE_HEADER)
  fout.write(TABLE_HEADER)
  fout.write(GetPageHeader(file_prefix, total_len, shard_size, i))
   
  start = i * shard_size
  end = min(start + shard_size, total_len)
  content = s[start: end]

  for line in content:
    if not line: continue
    (sn, name, when, ip, topic, link, same_topic_link) = line.split("|", 6)
    if same_topic_link:
      sametopic = '<a href="%s"> Same topic</a>' % same_topic_link
    else:
      sametopic = ""
    fout.write(TABLE_ROW % {"sn": sn, "name": name, "ip": ip, "topic": topic,
                       "link": link, "sametopic": sametopic})
    
  fout.write(PAGE_FOOTER)
  fout.close()


if __name__ == '__main__':
  main(sys.argv)
